package com.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MCSLock implements Lock {

	public static class QNode {
		volatile boolean lock;
		volatile QNode next;
	}

	private AtomicReference<QNode> tail;

	private ThreadLocal<QNode> myNode;

	public MCSLock() {
		tail = new AtomicReference<MCSLock.QNode>(null);
		myNode = new ThreadLocal<QNode>() {
			protected QNode initialValue() {
				return new QNode();
			}
		};
	}

	@Override
	public void lock() {
		QNode node = myNode.get();
		QNode preNode = tail.getAndSet(node);
		node.lock = true;
		preNode.next = node;
		while (node.lock) {

		}
	}

	@Override
	public void unlock() {
		// TODO Auto-generated method stub

	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean tryLock() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}
